<template>
  <d2-container>
    <div class="mod-tenant-account">
      <!-- 左侧树形结构 -->
      <div class="left-tree-panel">
        <div class="tree-search">
          <el-input 
            v-model="treeSearchText" 
            placeholder="请输入楼栋内容" 
            size="small" 
            clearable>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <div class="tree-container">
          <el-tree
            :data="treeData"
            :props="treeProps"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            :expand-on-click-node="false"
            @node-click="handleNodeClick">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </div>
      </div>
      <!-- 右侧内容区域 -->
      <div class="right-content-panel">
        <!-- 操作栏 -->
        <div class="operation-bar">
          <el-button type="primary" size="small" @click="addOrUpdateHandle()">
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </div>
        <!-- 标签页 -->
        <div class="tab-container">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="租户信息" name="tenant"></el-tab-pane>
            <el-tab-pane label="租户管理" name="management"></el-tab-pane>
          </el-tabs>
        </div>
        <!-- 表格 -->
        <el-table
          :data="dataList"
          border
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          style="width: 100%;">
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50">
          </el-table-column>
          
          <!-- 租户信息标签页的列 -->
          <template v-if="activeTab === 'tenant'">
            <el-table-column
              prop="roomNumber"
              header-align="center"
              align="center"
              label="房间号">
            </el-table-column>
            <el-table-column
              prop="userName"
              header-align="center"
              align="center"
              label="用户名">
            </el-table-column>
            <el-table-column
              prop="contactPhone"
              header-align="center"
              align="center"
              label="联系电话">
            </el-table-column>
            <el-table-column
              prop="loginPassword"
              header-align="center"
              align="center"
              label="登录密码">
            </el-table-column>
            <el-table-column
              prop="contactAddress"
              header-align="center"
              align="center"
              label="联系地址">
            </el-table-column>
            <el-table-column
              prop="totalMeter"
              header-align="center"
              align="center"
              label="合计计量">
            </el-table-column>
            <el-table-column
              prop="createTime"
              header-align="center"
              align="center"
              label="创建时间">
            </el-table-column>
          </template>
          
          <!-- 租户管理标签页的列 -->
          <template v-else>
            <el-table-column
              prop="roomNumber"
              header-align="center"
              align="center"
              label="房间号">
            </el-table-column>
            <el-table-column
              prop="userName"
              header-align="center"
              align="center"
              label="用户名">
            </el-table-column>
            <el-table-column
              prop="paymentMethod"
              header-align="center"
              align="center"
              label="付费方式">
              <template slot-scope="scope">
                <el-select v-model="scope.row.paymentMethod" size="mini" placeholder="请选择">
                  <el-option label="预付费" value="prepaid"></el-option>
                  <el-option label="后付费" value="postpaid"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="electricPlan"
              header-align="center"
              align="center"
              label="电价方案">
              <template slot-scope="scope">
                <el-select v-model="scope.row.electricPlan" size="mini" placeholder="请选择">
                  <el-option label="方案一" value="plan1"></el-option>
                  <el-option label="方案二" value="plan2"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="timePlan"
              header-align="center"
              align="center"
              label="定时方案">
              <template slot-scope="scope">
                <el-select v-model="scope.row.timePlan" size="mini" placeholder="请选择">
                  <el-option label="方案一" value="time1"></el-option>
                  <el-option label="方案二" value="time2"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="waterPlan"
              header-align="center"
              align="center"
              label="水价方案">
              <template slot-scope="scope">
                <el-select v-model="scope.row.waterPlan" size="mini" placeholder="请选择">
                  <el-option label="方案一" value="water1"></el-option>
                  <el-option label="方案二" value="water2"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="subsidyPlan"
              header-align="center"
              align="center"
              label="补助方案">
              <template slot-scope="scope">
                <el-select v-model="scope.row.subsidyPlan" size="mini" placeholder="请选择">
                  <el-option label="方案一" value="subsidy1"></el-option>
                  <el-option label="方案二" value="subsidy2"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="depositAmount"
              header-align="center"
              align="center"
              label="催缴金额">
              <template slot-scope="scope">
                <el-input v-model="scope.row.depositAmount" size="mini" placeholder="请输入"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="feeAmount"
              header-align="center"
              align="center"
              label="费控金额">
              <template slot-scope="scope">
                <el-input v-model="scope.row.feeAmount" size="mini" placeholder="请输入"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="publicAmount"
              header-align="center"
              align="center"
              label="公摊费用">
              <template slot-scope="scope">
                <el-input v-model="scope.row.publicAmount" size="mini" placeholder="请输入"></el-input>
              </template>
            </el-table-column>
          </template>
          
          <el-table-column
            header-align="center"
            align="center"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
              <el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          class="mt-4"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    </div>
  </d2-container>
</template>
<script>
import AddOrUpdate from './account-add-or-update'
export default {
  name: 'tenant-account',
  data() {
    return {
      treeSearchText: '',
      treeData: [],
      selectedNode: null,
      treeProps: {
        children: 'children',
        label: 'label'
      },
      activeTab: 'tenant',
      dataForm: {
        userName: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false
    }
  },
  components: {
    AddOrUpdate
  },
  watch: {
    treeSearchText(val) {
      this.$refs.tree.filter(val)
    }
  },
  activated() {
    this.getTreeData()
    this.getDataList()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleNodeClick(data) {
      console.log('选中节点:', data)
      this.selectedNode = data
      // 如果选中的是房间节点（有roomId属性），则根据房间过滤数据
      this.getDataList()
    },
    handleTabClick(tab) {
      this.getDataList()
    },
    // 获取树形结构数据
    async getTreeData() {
      try {
        const data = await this.$api.tenant_tree_list()
        this.treeData = data.data
      } catch (error) {
        console.error('获取树形数据失败:', error)
        this.$message.error('获取树形数据失败')
      }
    },
    // 获取数据列表
    async getDataList(type) {
      if (type) {
        this.pageIndex = 1
      }
      this.dataListLoading = true
      try {
        const params = {
          page: this.pageIndex,
          limit: this.pageSize,
          tab: this.activeTab
        }
        
        // 如果选中了房间节点，添加房间ID参数
        if (this.selectedNode && this.selectedNode.roomId) {
          params.roomId = this.selectedNode.roomId
        }
        
        const data = await this.$api.tenant_account_list(params)
        this.dataList = data.data.page.list
        this.totalPage = data.data.page.totalCount
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.dataListLoading = false
      }
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 删除
    deleteHandle(id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.tenant_account_delete({ ids })
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList()
            }
          })
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    }
  }
}
</script>
<style scoped>
.mod-tenant-account {
  display: flex;
  height: calc(100vh - 120px);
}
.left-tree-panel {
  width: 300px;
  border-right: 1px solid #e6e6e6;
  padding: 20px;
  background: #fff;
}
.tree-search {
  margin-bottom: 20px;
}
.tree-container {
  height: calc(100% - 60px);
  overflow-y: auto;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.right-content-panel {
  flex: 1;
  padding: 20px;
  background: #fff;
  display: flex;
  flex-direction: column;
}
.operation-bar {
  margin-bottom: 20px;
}
.tab-container {
  margin-bottom: 20px;
}
.tab-container .el-tabs__header {
  margin: 0;
}
.mt-4 {
  margin-top: 20px;
}
/* 表格样式调整 */
.el-table {
  flex: 1;
}
.el-table .el-select,
.el-table .el-input {
  width: 100%;
}
.el-table .el-select .el-input__inner,
.el-table .el-input__inner {
  border: none;
  background: transparent;
  text-align: center;
}
.el-table .el-select .el-input__inner:focus,
.el-table .el-input__inner:focus {
  border: 1px solid #409eff;
  background: #fff;
}
</style>
